﻿namespace Digitalmes.Application.Sys.Roles.Commands;

/// <summary>
/// 创建角色命令。
/// </summary>
public record CreateRoleCommand(SysRoleDto Role) : IRequest<IResult<bool>>;

internal sealed class CreateRoleCommandHandler(IRepository<SysRole> repo) : IRequestHandler<CreateRoleCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
    {
        // 检查账号名是否已存在。
        if (await repo.IsAnyAsync(m => m.Code == request.Role.Code, cancellationToken))
        {
            return Result.Failure("角色编号已存在");
        }

        var role = request.Role.Adapt<SysRole>();
        var ok = await repo.InsertAsync(role, cancellationToken);
        return Result.From(ok);
    }
}
